﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace HitchHikersGuideToTheGalaxy.Models
{
    public class TourRepository : ITourRepository
    {
        GalaxyDataContext db = new GalaxyDataContext();

        #region Default Add, Delete and save actions

        /// <summary>
        /// Add one tour
        /// </summary>
        /// <param name="tour">Object tour</param>
        public void Add(Tour tour)
        {
            db.Tours.InsertOnSubmit(tour);
        }

        /// <summary>
        /// Delete one Tour object
        /// </summary>
        /// <param name="tour">Object Tour</param>
        public void Delete(Tour tour)
        {
            db.Passengers.DeleteAllOnSubmit(tour.Passengers);
            db.Tours.DeleteOnSubmit(tour);
        }

        /// <summary>
        /// Save changes to the database.
        /// </summary>
        public void Save()
        {
            db.SubmitChanges();
        }

        #endregion

        #region Querys

        /// <summary>
        /// Find all tours
        /// </summary>
        /// <returns>Tour collection</returns>
        public IQueryable<Tour> FindAllTours()
        {
            return from tour in db.Tours
                   orderby tour.Time
                   select tour;
        }

        /// <summary>
        /// Find all upcoming tours
        /// </summary>
        /// <returns>Tour collection</returns>
        public IQueryable<Tour> FindUpcomingTours()
        {
            return from tour in db.Tours
                   where tour.Time > DateTime.Now
                   orderby tour.Time
                   select tour;
        }

        /// <summary>
        /// Get one tour by id.
        /// </summary>
        /// <param name="id">Id of the tour</param>
        /// <returns>Tour object</returns>
        public Tour GetTour(int id)
        {
            return db.Tours.SingleOrDefault(d => d.Id == id);
        }

        #endregion
    }
}
